package async.callback;

import org.apache.commons.lang3.StringUtils;

/**
 * @auther zhouliangliang
 * @date 2022/10/8 23:15
 * @description
 */
public class AsyncDemo {

    private interface Callback{
        void doOnError(Exception e);
        void doOnSuccess(String value);
    }

    private static class A{
        public void invokeB(String value) {
            System.out.println("invoke B " + Thread.currentThread().getName());
            B b = new B();
            b.doSomething(value, new Callback() {
                @Override
                public void doOnError(Exception e) {
                    System.out.println("in class A method doOnError!");
                }

                @Override
                public void doOnSuccess(String value) {
                    System.out.println("doOnSuccess " + Thread.currentThread().getName());
                    System.out.println("in class A method doOnSuccess!");
                }
            });

            System.out.println("exit invokeB");
        }
    }

    private static class B{
        public void doSomething(String value, Callback callback) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    //do something
                    try {
                        Thread.sleep(10000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if(StringUtils.isEmpty(value)) {
                        callback.doOnError(new Exception("value is empty"));
                    } else {
                        callback.doOnSuccess(new StringBuilder(value).reverse().toString());
                    }
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
            System.out.println("doSomething " + thread.getName());
        }
    }

    public static void main(String[] args) throws Exception{
        A a = new A();
        a.invokeB("123456");
    }
}
